package cn.oldfeel.spark.db;

import java.util.ArrayList;

import org.jivesoftware.smack.packet.Message;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import cn.oldfeel.spark.config.UserInfo;
import cn.oldfeel.spark.item.HistoryItem;
import cn.oldfeel.spark.item.MsgItem;
import cn.oldfeel.spark.util.DateUtil;

/**
 * 聊天数据库帮助类
 * 
 * @author oldfeel
 * @create Date:2013年11月6日下午2:50:15
 */
public class ChatDbHelper extends SQLiteOpenHelper {

	private static final String DB_NAME = "chat_db";
	private static final int DB_VERSION = 1;
	private static final String TABLE_NAME = "spark";
	private static ChatDbHelper dbHelper;
	private SQLiteDatabase db;
	private Context context;

	public static ChatDbHelper getInstance(Context context) {
		if (dbHelper == null) {
			dbHelper = new ChatDbHelper(context);
			dbHelper.db = dbHelper.getWritableDatabase();
		}
		return dbHelper;
	}

	public ChatDbHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}

	public ChatDbHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE spark ( \n"
				+ "    _id      INTEGER PRIMARY KEY AUTOINCREMENT\n"
				+ "                     UNIQUE,\n"
				+ "    msg_from TEXT    NOT NULL,\n"
				+ "    msg_to TEXT    NOT NULL,\n"
				+ "    msg_body TEXT    NOT NULL,\n"
				+ "    msg_time TEXT    NOT NULL,\n" + "    status   INT \n"
				+ ");\n" + "");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	/**
	 * 获取历史列表
	 * 
	 * @return
	 */
	public ArrayList<HistoryItem> getHistoryList() {
		ArrayList<HistoryItem> list = new ArrayList<HistoryItem>();
		Cursor cursor = db.rawQuery(
				"select sum(status) as count, msg_from, msg_body, msg_time from "
						+ TABLE_NAME + " group by msg_from order by _id desc;",
				null);
		String myName = UserInfo.getInstance(context).getName();
		while (cursor.moveToNext()) {
			HistoryItem item = new HistoryItem(cursor);
			// 如果msg_from不是本人,添加到历史记录列表中
			if (!item.from.equals(myName)) {
				list.add(item);
			}
		}
		return list;
	}

	/**
	 * 插入消息记录
	 * 
	 * @param msg
	 */
	public void insertMsg(Message msg) {
		String from = msg.getFrom();
		String to = msg.getTo();
		String body = msg.getBody();
		String time = (String) msg.getProperty("time");
		if (time == null || time.length() == 0) {
			time = DateUtil.getCurDateStr();
		}
		ContentValues values = new ContentValues();
		values.put("msg_from", from);
		values.put("msg_body", body);
		values.put("msg_to", to);
		values.put("msg_time", time);
		db.insert(TABLE_NAME, "_id", values);
	}

	public void insertMsg(MsgItem msg) {
	}
}
